package com.ml.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ml.service.MsmService;
import com.ml.utils.ConstantPropertiesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 短信服务
 *
 * @author ShuHaoNan
 * @email shuhaonan1@gmail.com
 * @date 2020/10/26 12:41
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信
     * @param param 验证码
     * @param phone 手机号
     * @return 是否发送成功
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        // 链接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        CommonRequest request = new CommonRequest();

        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com"); // 不能修改
        request.setSysVersion("2017-05-25"); // 不能修改
        request.setSysAction("SendSms");

        // 自定义的参数 （手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phone); // 要发送的手机号
        request.putQueryParameter("SignName", ConstantPropertiesUtils.SIGN_NAME); // 签名
        request.putQueryParameter("TemplateCode", ConstantPropertiesUtils.TEMPLATE_CODE); // 阿里云模板CODE
        // 构建一个短信的验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取验证码
     *
     * @param phone 手机号
     */
    @Override
    public String getCode(String phone) {
        String code = (String) redisTemplate.opsForValue().get(phone);
        return code;
    }
}
